<template>
  <div class="carlist">
    <myheader title="购物车">
      <template #left>
        <van-icon name="arrow-left" @click="$router.back()" />
      </template>
    </myheader>
    <van-checkbox-group v-model="result" ref="checkboxGroup" icon-size="30">
      <van-swipe-cell v-for="(good, index) in goodsList" :key="good.id">
        <!-- <van-switch v-model="good.checked" inactive-color="#ccc" /> -->

        <van-checkbox :name="good.id"></van-checkbox>
        <van-card
          :price="good.sell_price"
          :desc="good.title"
          class="goods-card"
          :thumb="good.thumb_path"
        >
          <template #footer>
            <van-stepper
              v-model="good.value"
              class="stepper"
              @plus="addGoods(good)"
              @minus="subGoods(good)"
            />
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="delGood(index, good.id)"
          />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox
        type="primary"
        @click="checkAll"
        v-model="checkedAll"
        class="checkAll checkGroup"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<script>
import { getShopCarList } from "@/api/car.js";
import myheader from "@/components/Header.vue";
import { EventBus } from "@/utils/eventBus.js";
export default {
  data() {
    return {
      goodsList: [],
      // 用来发请求的数组，里面存着id
      goodsReqGroup: [],

      // totalPrice: 311100,
      checked: false,
      checkedAll: false,
      result: [],
      // totalNum: 0,
    };
  },
  components: {
    myheader,
  },
  methods: {
    onSubmit() {
      // this.goodsList[0].checked = !this.goodsList[0].checked;
      this.$toast.success("你成功消费了" + this.totalPrice + "￥!");
      console.log(this.result);

      //在goodsList里面过滤出选择的物品然后返回
      this.goodsList = this.goodsList.filter((v) => {
        return this.result.indexOf(v.id) == -1;
      });
      //拿到本地的数据之后过滤出选择的商品然后又存进去
      let temp = JSON.parse(localStorage.getItem("goodsGroup"));
      temp = temp.filter((v) => {
        return this.result.indexOf(v.id) == -1;
      });

      localStorage.setItem("goodsGroup", JSON.stringify(temp));
    },
    delGood(index, id) {
      this.goodsList.splice(index, 1);
      // 明天来改，因为直接把整个group存进去的话，有其他数据影响，要搞成{id:1,num:1}这种样子才行
      localStorage.setItem("goodsGroup", JSON.stringify(this.goodsList));
    },

    addGoods(goods) {
      goods.value++;
      let tempGroup = JSON.parse(localStorage.getItem("goodsGroup"));
      tempGroup.push({
        id: goods.id,
        num: 1,
      });
      localStorage.setItem("goodsGroup", JSON.stringify(tempGroup));
      this.$toast.success("");
    },
    subGoods(goods) {
      goods.value--;
      let tempGroup = JSON.parse(localStorage.getItem("goodsGroup"));
      tempGroup.push({
        id: goods.id,
        num: -1,
      });
      localStorage.setItem("goodsGroup", JSON.stringify(tempGroup));
    },

    //全选的方法
    checkAll() {
      this.$refs.checkboxGroup.toggleAll({
        checked: this.checkedAll,
        skipDisabled: true,
      });
      console.log(this.result);
    },
  },
  computed: {
    //总价的计算
    totalPrice() {
      let sum = 0;
      this.goodsList.forEach((v) => {
        if (this.result.indexOf(v.id) != -1) {
          sum += v.value * v.sell_price;
        }
      });
      return sum * 100;
    },
  },
  watch: {
    // 用来控制全选按钮的开关
    result() {
      if (
        this.result.length == 0 ||
        this.result.length != this.goodsList.length
      ) {
        this.checkedAll = false;
      } else {
        this.checkedAll = true;
      }
    },
    goodsList: {
      handler(newV, oldV) {
        let total = 0;
        newV.forEach((item) => {
          total += item.value;
        });
        // console.log(total);
        EventBus.$emit("sendNum", total);
      },
      immediate: true,
      deep: true,
    },
  },
  async mounted() {
    let tempGoodsGroup = JSON.parse(localStorage.getItem("goodsGroup"));
    //如果本地数据存在的id，请求数组没有的话，存入请求数组
    if (tempGoodsGroup) {
      tempGoodsGroup.forEach((item) => {
        if (this.goodsReqGroup.indexOf(item.id) == -1) {
          this.goodsReqGroup.push(item.id);
        }
      });
    }

    this.goodsReqGroup.forEach((item) => {
      let tempObj = { id: item, value: 0 };
      tempGoodsGroup.forEach((id) => {
        if (item == id.id) {
          tempObj.value += id.num;
        }
      });
      this.goodsList.push(tempObj);
    });
    if (this.goodsList.length !== 0) {
      //根据请求数组获取
      let res = await getShopCarList(this.goodsReqGroup.toString());
      let arr1 = res.data.message;
      arr1.forEach((item, index) => {
        this.goodsList[index].title = item.title;
        this.goodsList[index].sell_price = item.sell_price;
        this.goodsList[index].thumb_path = item.thumb_path;

        // 这两句话是用来刷新页面的，不刷新数据出不来，需要重新写
        this.goodsList[index].value += 1;
        this.goodsList[index].value -= 1;
      });
    }
  },
};
</script>

<style lang="less" scoped>
.carlist {
  padding-bottom: 100px;
  /deep/.van-swipe-cell__wrapper {
    display: flex;
    align-items: center;
    padding: 20px 5px;
    border-bottom: 4px solid #ccc;
  }
  .stepper {
    // margin-top: 65px;
    padding-top: 19px;
  }
  .goods-card {
    .van-card__desc {
      color: rgb(115, 221, 221);
      font-size: 15px;
      //   overflow: hidden;
      //   text-overflow: ellipsis;
      //   -webkit-box-orient: vertical;
      //   -webkit-line-clamp: 3; /*行数*/
    }

    .van-image {
      width: 100%;
    }
    .van-card__header {
      display: flex;
      height: 12vw;
    }
    .van-card__content {
      width: 46vw;
    }
    .van-card__price {
      color: red;
      font-size: 15px;
      .van-card__price-integer {
        font-size: 15px;
      }
    }
    margin: 0;
    background-color: white;
  }

  .delete-button {
    height: 100%;
  }
  .van-submit-bar {
    margin-bottom: 50px;
  }
  .checkAll {
    margin-right: 10px;
    padding-left: 20px;
  }
  .checkGroup {
    margin-top: 3px;
  }
}
</style>